<template>
  <div class="user-management">
    <el-card class="box-card">
      <div slot="header" class="card-header">
        <span>用户管理</span>
      </div>
      
      <div class="search-bar">
        <el-input
          placeholder="用户名"
          v-model="searchParams.nickname"
          class="search-input"
          clearable
          @clear="handleSearch">
        </el-input>
        <el-input
          placeholder="手机号"
          v-model="searchParams.phone"
          class="search-input"
          clearable
          @clear="handleSearch">
        </el-input>
        <el-select v-model="searchParams.role" placeholder="角色筛选" clearable @change="handleSearch">
          <el-option label="普通用户" :value="1"></el-option>
          <el-option label="社联管理员" :value="2"></el-option>
          <el-option label="超级管理员" :value="3"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
      
      <el-table
        v-loading="loading"
        :data="filteredUserList"
        style="width: 100%"
        border>
        <el-table-column
          type="index"
          label="#"
          width="80"
          align="center">
        </el-table-column>
        <el-table-column
          prop="avatar"
          label="头像"
          width="80"
          align="center">
          <template slot-scope="scope">
            <el-avatar :src="scope.row.avatar" :size="40"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column
          prop="nickname"
          label="用户名"
          width="120">
        </el-table-column>
        <el-table-column
          prop="phone"
          label="手机号"
          width="120">
        </el-table-column>
        <el-table-column
          prop="dept"
          label="学院"
          width="120">
          <template slot-scope="scope">
            {{ getDeptName(scope.row.dept) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="role"
          label="角色"
          width="120"
          align="center">
          <template slot-scope="scope">
            <el-tag :type="getRoleType(scope.row.role)">
              {{ getRoleName(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="stat"
          label="状态"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-switch
              
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="createTime"
          label="注册时间"
          width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="handleEditUser(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDeleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="500px">
      <el-form 
        ref="userForm" 
        :model="userForm" 
        :rules="userRules" 
        label-width="100px">
        <el-form-item label="用户名" prop="nickname">
          <el-input v-model="userForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" disabled></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="dept">
          <el-select v-model="userForm.dept" placeholder="请选择学院">
            <el-option 
              v-for="(deptName, deptId) in deptMap" 
              :key="deptId" 
              :label="deptName" 
              :value="Number(deptId)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option :value="1" label="普通用户"></el-option>
            <el-option :value="2" label="社联管理员"></el-option>
            <el-option :value="3" label="超级管理员"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="状态" prop="status">
          <el-switch
            v-model="userForm.status"
            active-value="1"
            inactive-value="0"
            active-text="正常"
            inactive-text="禁用">
          </el-switch>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUserForm" :loading="submitting">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import httpInstance from '@/utils/http';

export default {
  name: 'UserManagement',
  data() {
    return {
      searchParams: {
        nickname: '',
        phone: '',
        role: ''
      },
      loading: false,
      userList: [],
      deptMap: {},
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      filteredUserList: [],
      editDialogVisible: false,
      userForm: {
        id: '',
        nickname: '',
        phone: '',
        dept: '',
        role: 1,
        status: '1'
      },
      userRules: {
        nickname: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        dept: [
          { required: true, message: '请选择学院', trigger: 'change' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      submitting: false
    };
  },
  computed: {
    filteredUserList() {
      // 如果后端已实现分页，直接返回 userList
      if (this.pagination.total > 0) {
        return this.userList;
      }
      
      // 如果后端未实现分页，在前端进行分页处理
      const startIndex = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const endIndex = startIndex + this.pagination.pageSize;
      return this.userList.slice(startIndex, endIndex);
    }
  },
  created() {
    this.fetchDeptList();
    this.fetchUserList();
  },
  methods: {
    
    // 获取部门列表
    async fetchDeptList() {
      try {
        const res = await httpInstance.get('/api/sys/dep');
        if (res.code === 200) {
          this.deptMap = res.data;
        } else {
          this.$message.error(res.msg || '获取学院列表失败');
        }
      } catch (error) {
        console.error('获取学院列表失败:', error);
        this.$message.error('获取学院列表失败');
      }
    },
    
    // 获取用户列表
    async fetchUserList() {
      this.loading = true;
      try {
        // 调用搜索接口
        const res = await httpInstance.post('/api/user/search', this.searchParams);
        
        if (res.code === 200) {
          // 保存完整用户列表
          this.userList = res.data || [];
          // 执行前端分页
          this.handleFrontendPagination();
        } else {
          this.$message.error(res.msg || '获取用户列表失败');
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        this.$message.error('获取用户列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 处理前端分页
    handleFrontendPagination() {
      const startIndex = (this.pagination.currentPage - 1) * this.pagination.pageSize;
      const endIndex = startIndex + this.pagination.pageSize;
      this.filteredUserList = this.userList.slice(startIndex, endIndex);
      this.pagination.total = this.userList.length;
    },
    
    // 处理搜索
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchUserList();
    },
    
    // 处理页码大小变化
    handleSizeChange(newSize) {
      this.pagination.pageSize = newSize;
      this.handleFrontendPagination();
    },
    
    // 处理页码变化
    handleCurrentChange(newPage) {
      this.pagination.currentPage = newPage;
      this.handleFrontendPagination();
    },
    
    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 获取学院名称
    getDeptName(deptId) {
      return this.deptMap[deptId] || '未知学院';
    },
    
    // 获取角色类型
    getRoleType(role) {
      const types = {
        1: '',        // 普通用户
        2: 'success', // 社联管理员
        3: 'danger'   // 超级管理员
      };
      return types[role] || '';
    },
    
    // 获取角色名称
    getRoleName(role) {
      const names = {
        1: '普通用户',
        2: '社联管理员',
        3: '超级管理员'
      };
      return names[role] || '未知角色';
    },
    
    // 处理用户状态变更
    async handleStatusChange(row) {
      try {
        const newStatus = row.status === 1 ? 0 : 1;
        
        const res = await httpInstance.post(`/api/admin/users/${row.id}/status`, {
          status: newStatus
        });
        
        if (res.code === 200) {
          this.$message.success(`用户状态已${newStatus === 1 ? '启用' : '禁用'}`);
          row.status = newStatus;
        } else {
          this.$message.error(res.msg || '更新用户状态失败');
          // 回滚UI状态
          row.status = newStatus === 1 ? 0 : 1;
        }
      } catch (error) {
        console.error('更新用户状态失败:', error);
        this.$message.error('更新用户状态失败');
        // 回滚UI状态
        row.status = row.status === 1 ? 0 : 1;
      }
    },
    
    // 处理编辑用户
    handleEditUser(row) {
      this.userForm = {
        id: row.id,
        nickname: row.nickname,
        phone: row.phone,
        dept: row.dept,
        role: row.role,
        status: row.status.toString()
      };
      this.editDialogVisible = true;
      
      // 延迟重置表单，确保DOM更新后操作
      this.$nextTick(() => {
        this.$refs.userForm && this.$refs.userForm.clearValidate();
      });
    },
    
    // 提交用户表单
    submitUserForm() {
      this.$refs.userForm.validate(async (valid) => {
        if (!valid) return;
        
        this.submitting = true;
        try {
          const userData = { ...this.userForm };
          
          const res = await httpInstance.put(`/api/admin/users/${userData.id}`, userData);
          
          if (res.code === 200) {
            this.$message.success('用户更新成功');
            this.editDialogVisible = false;
            this.fetchUserList();
          } else {
            this.$message.error(res.msg || '更新用户失败');
          }
        } catch (error) {
          console.error('更新用户失败:', error);
          this.$message.error('更新用户失败');
        } finally {
          this.submitting = false;
        }
      });
    },
    
    // 处理删除用户
    async handleDeleteUser(row) {
      try {
        await this.$confirm(`确定要删除用户 ${row.nickname} 吗? 此操作不可恢复!`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const res = await httpInstance.delete(`/api/admin/users/${row.id}`);
        
        if (res.code === 200) {
          this.$message.success('用户删除成功');
          this.fetchUserList();
        } else {
          this.$message.error(res.msg || '删除用户失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error);
          this.$message.error('删除用户失败');
        }
      }
    }
  }
};
</script>

<style scoped>
.user-management {
  padding: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-input {
  width: 200px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>